package sctu.edu.java.year2016.team01.xuhanmei.day20160619;

import java.io.*;

/**
 * Created by Administrator on 2016/6/19.
 */
public class LearnIO {
    public static void main(String[] args) {
        String parentpath = "d:/java小程序";//以相对路径创建文件
        String childname = "LearnIO.txt";
        File file = new File(parentpath, childname);

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //       String WanttoWrite="好饿啊，好想吃莽莽，可是程序还没有写完！\r\n";

        String WanttoWrite = "ahfigugusrb\r\n";


        OutputStream os = null;
        try {
            os = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte[] bytes = WanttoWrite.getBytes();


        try {
            os.write(bytes, 0, WanttoWrite.length());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写出失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭输出流失败！");
                }
            }

        }


        InputStream is = null;
        try {
            is=new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] b = new byte[1024];
        int len = 0;
        try {
            while (-1 != (len = is.read(b))) {
                String info = new String(b, 0, len);
                System.out.println(info);

            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件失败");
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
